from flask import Blueprint, jsonify
from web.models import MovieData, db, SpiderRunInfo
from sqlalchemy import func
import requests

api_view = Blueprint('api', __name__)


class ShiCi:
    def __init__(self):
        self.token_url = 'https://v2.jinrishici.com/token'
        self.shi_ci_url = 'https://v2.jinrishici.com/sentence'

    def get_token(self):
        response = requests.get(self.token_url).json()
        if response['status'] == 'success':
            return response['data']
        return None

    def get_shiCi(self):
        token = self.get_token()
        if token is None:
            return None
        headers = {
            'X-User-Token': token
        }
        response = requests.get(self.shi_ci_url, headers=headers).json()
        if response['status'] == 'success':
            return response['data']
        return None


@api_view.route('/yiYan')
def yiYan():
    shi_ci = ShiCi().get_shiCi()
    return jsonify(shi_ci)


# 饼图
@api_view.route('/movie/pie')
def movie_pie():
    data_list = []
    movie_data = db.session.query(
        MovieData.score.label('score'), func.count(MovieData.score).label('score_count')
    ).order_by(MovieData.score.desc()).group_by(MovieData.score).all()
    for i in movie_data:
        data_list.append({"value": i.score_count, "name": i.score})
    return jsonify({"code": 200, "data": data_list})


# 柱状图
@api_view.route('/movie/bar')
def movie_bar():
    score_list = []
    movie_name = []
    movie_data = db.session.query(
        MovieData.title.label('title'), MovieData.score.label('score')
    ).order_by(MovieData.score.desc()).limit(10).all()
    for i in movie_data:
        score_list.append(i.score)
        movie_name.append(i.title)
    return jsonify({"code": 200, "data": {"score_list": score_list, "movie_name": movie_name}})


# 散点图
@api_view.route('/movie/scatter')
def movie_scatter():
    movie_data = db.session.query(
        MovieData.film_length.label('film_length'), MovieData.score.label('score')
    ).order_by(MovieData.film_length.desc()).all()
    data_list = []
    for i in movie_data:
        data_list.append([i.film_length, i.score])
    return jsonify({"code": 200, "data": data_list})


# 折线图
@api_view.route('/movie/line')
def movie_line():
    year_list = []
    year_count = []
    movie_data = db.session.query(
        MovieData.year.label('year'), func.count(MovieData.year).label('year_count')
    ).order_by(MovieData.year.desc()).group_by(MovieData.year).all()
    for i in movie_data:
        year_list.append(i.year)
        year_count.append(i.year_count)
    return jsonify({"code": 200, "data": {"year_list": year_list, "year_count": year_count}})


# 矩形树图（电影类型）
@api_view.route('/movie/treemap')
def movie_treemap():
    data_list = []
    movie_data = db.session.query(
        func.substring_index(MovieData.movie_type, '/', 1).label('movie_type'),
        func.count(MovieData.movie_type).label('movie_type_count')
    ).group_by(
        func.substring_index(MovieData.movie_type, '/', 1)
    ).all()
    for i in movie_data:
        data_list.append({"name": i.movie_type, "value": i.movie_type_count})
    return jsonify({"code": 200, "data": data_list})


# 词云（电影的评论人数）
@api_view.route('/movie/wordcloud')
def movie_wordcloud():
    data_list = []
    movie_data = db.session.query(
        MovieData.title.label('title'), MovieData.people_num.label('people_num')
    ).order_by(MovieData.people_num.desc()).limit(100).all()
    for i in movie_data:
        data_list.append({"name": i.title, "value": i.people_num})
    return jsonify({"code": 200, "data": data_list})


@api_view.route('/movie/update_time')
def movie_update_time():
    spider_run_info = SpiderRunInfo.query.order_by(SpiderRunInfo.run_time.desc()).first()
    if spider_run_info:
        return jsonify({"code": 200, "update_time": spider_run_info.run_time.strftime("%Y-%m-%d %H:%M:%S")})
    return jsonify({"code": 400, "message": "暂无更新时间"})
